package com.lincoln.framework.interfaces;

import com.lincoln.framework.bean.NettyContext;
import io.netty.channel.ChannelHandlerContext;
import lombok.Getter;
import lombok.Setter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 设备信息
 *
 * @param <T>
 * @author lincoln
 */
public abstract class BaseDeviceInfo<T> {
    /**
     * 在attributes中存储未携带登陆状态请求服务器的次数
     */
    public static final String NO_LOGIN_REQUEST_TIME = "NO_LOGIN_REQUEST_TIME";
    /**
     * 总请求次数
     */
    public static final String REQUEST_TIME = "REQUEST_TIME";

    @Getter
    @Setter
    protected String clientId;

    @Getter
    @Setter
    protected Map<String, Object> attributes = new ConcurrentHashMap<>();

    @Getter
    @Setter
    protected String ip;

    @Getter
    @Setter
    protected int port;

    @Getter
    @Setter
    protected ChannelHandlerContext channelHandlerContext;

    /**
     * 验证登陆状态,是则从未登录列表中去掉
     *
     * @return
     */
    public boolean login() {
        if (isLogin()) {
            NettyContext.removeNoLogin(clientId);
            return true;
        } else {
            return false;
        }
    }

    /**
     * z注销客户端
     *
     * @return
     */
    public boolean logout() {
        if (!getChannelHandlerContext().isRemoved()) {
            getChannelHandlerContext().channel().close();
        }
        return true;
    }

    /**
     * 是否是登陆了的
     *
     * @return
     */
    public abstract boolean isLogin();

    /**
     * 获取主键(设备号,mac地址,imei等唯一值)
     *
     * @return
     */
    public abstract T getPrimaryKey();

    /**
     * 获取设备类型
     *
     * @return
     */
    public abstract Integer getDeviceType();

    /**
     * 获取设备类型
     *
     * @return
     */
    public abstract Integer getProtocolType();


    /**
     * 向此设备发送一个消息
     *
     * @param protocol
     * @return
     */
    public boolean sendMsg(BaseProtocol protocol) {
        if (this.getChannelHandlerContext() != null) {
            this.getChannelHandlerContext().writeAndFlush(protocol);
            return true;
        } else {
            return false;
        }
    }
}
